import cv2
import uuid
import base64
from PIL import Image
import os

def get_name():
    uuid_str = uuid.uuid4().hex
    file_name = uuid_str + ".png"
    return file_name

def photo():
    cap = cv2.VideoCapture(0)
    # 从摄像头获取图像，第一个为布尔变量表示成功与否，第二个变量是图像
    ret, filename = cap.read()
    # 保存图像至Haar相同路径
    img_name = get_name()
    cv2.imwrite('./Pic/'+img_name, filename)
    # 释放摄像头资源
    cap.release()
    imagefile = "./Pic/"+img_name
    targetfile= "./Pic/"+img_name
    img = Image.open(imagefile)  # 返回一个Image对象

    # os模块中的path目录下的getSize()方法获取文件大小，单位字节Byte
    size = os.path.getsize(imagefile)  # 计算图片大小即KB
    # size的两个参数
    width, height = img.size[0], img.size[1]
    # 用于保存压缩过程中的temp路径,每次压缩会被不断覆盖
    newPath = 'temp.jpg'
    while size > 1024*1024*5:
        width, height = round(width * 0.9), round(height * 0.9)
        print(width, height)
        img = img.resize((width, height), Image.ANTIALIAS)
        img.save(newPath)
        size = os.path.getsize(newPath)
    # 压缩完成
    img.save(targetfile)
    img = Image.open(imagefile)  # 返回一个Image对象
    img.show()
    return img_name

def pic_to_base64(name):
    with open("./Pic/"+name, "rb") as f:  # 转为二进制格式
        base64_data = base64.b64encode(f.read())  # 使用base64进行加密
        return base64_data

def pic_to_url(name):
    answer = "http://pic.cpolar.cn/"+name
    return answer

if __name__ == '__main__':
    name=photo()
    print(name)
    print(pic_to_url(name))